﻿DECLARE @StatDate datetime
SET @StatDate = DATEADD(D, 0, DATEDIFF(D, 256, GETDATE()))
SELECT
        @StatDate,
        md.to_abonent_id AS ap_id,
        md.msg_category,
        count(md.hostname_id) AS msg_cnt,
        sum(md.msg_size) AS msg_size
      FROM mon400_data md
      WHERE
        (md.datetime_in BETWEEN (@StatDate) AND (@StatDate + 1)) and
        (md.msg_kind = 0) AND   /* только входящие письма от АП */
        (md.msg_cirkul = 0)     /* уберем лишние циркуляры */
GROUP BY md.to_abonent_id, md.msg_category
ORDER BY ap_id, msg_cnt DESC 